package com.xtianzhuang.www.study2019.mq;

import javax.annotation.PreDestroy;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.aliyun.openservices.ons.api.order.OrderProducer;

public class MqSend {

	private OrderProducer producer;

	private String isUseONS;

	private String producerId;

	private String accessKey;

	private String secretKey;

	private String namesrvAddr;

	private String onsAddr;

	private String tags;
	/**
	* kafka生产者消息发送方法
	*
	* @param topicName 主题
	* @param key       分区的key
	* @param message   消息
	*/
	public void send(String topicName, String key, String message) {
		if (topicName == null || key == null || message == null) {
			return;
		}
		Message msg = new Message( //
				// Message所属的Topic
				topicName,
				// Message Tag 可理解为Gmail中的标签，对消息进行再归类，方便Consumer指定过滤条件在MQ服务器过滤
				tags,
				// Message Body 可以是任何二进制形式的数据， MQ不做任何干预
				// 需要Producer与Consumer协商好一致的序列化和反序列化方式
				message.getBytes());
		// 设置代表消息的业务关键属性，请尽可能全局唯一
		// 以方便您在无法正常收到消息情况下，可通过MQ 控制台查询消息并补发
		// 注意：不设置也不会影响消息正常收发
		msg.setKey(key);
		// 发送消息，只要不抛异常就是成功
		try {
			producer.send(msg, key);
		} catch (ONSClientException e) {
			System.out.println(e.getMessage());
		}
	}

	@PreDestroy
	public void close() {
		if (producer != null) {
			producer.shutdown();
		}
	}

	public OrderProducer getProducer() {
		return producer;
	}

	public void setProducer(OrderProducer producer) {
		this.producer = producer;
	}

	public String getIsUseONS() {
		return isUseONS;
	}

	public void setIsUseONS(String isUseONS) {
		this.isUseONS = isUseONS;
	}

	public String getProducerId() {
		return producerId;
	}

	public void setProducerId(String producerId) {
		this.producerId = producerId;
	}

	public String getAccessKey() {
		return accessKey;
	}

	public void setAccessKey(String accessKey) {
		this.accessKey = accessKey;
	}

	public String getSecretKey() {
		return secretKey;
	}

	public void setSecretKey(String secretKey) {
		this.secretKey = secretKey;
	}

	public String getNamesrvAddr() {
		return namesrvAddr;
	}

	public void setNamesrvAddr(String namesrvAddr) {
		this.namesrvAddr = namesrvAddr;
	}

	public String getOnsAddr() {
		return onsAddr;
	}

	public void setOnsAddr(String onsAddr) {
		this.onsAddr = onsAddr;
	}

	public String getTags() {
		return tags;
	}

	public void setTags(String tags) {
		this.tags = tags;
	}


}
